package LeetCode;

import java.util.ArrayList;

public class LC_093_RestoreIPAddresses {
    public static void main(String[] args) {

    }

    static class Solution {
        public ArrayList<String> restoreIpAddresses(String s) {
            ArrayList<String> res = new ArrayList<>();
            String item = new String();
            if (s.length() < 4 || s.length() > 12) return res;
            dfs(s, 0, item, res);
            return res;
        }

        private void dfs(String s, int start, String item, ArrayList<String> res) {
            if (start == 3 && isValid(s)) {
                res.add(item + s);
                return;
            }
            for (int i = 0; i < 3 && i < s.length() - 1; i++) {
                String subStr = s.substring(0, i + 1);
                if (isValid(subStr))
                    dfs(s.substring(i + 1, s.length()), start + 1, item + subStr + '.', res);
            }
        }

        private boolean isValid(String s) {
            if (s.charAt(0) == '0')
                return s.equals("0");
            int num = Integer.parseInt(s);
            return num <= 255 && num > 0;
        }
    }
}
